package org.example.daily;

import java.util.Date;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class provCons {
    public static void main(String[] args) {
        Cake cake = new Cake();
        for (int i = 0; i < 20; i++) {
            new Thread(cake::increment).start();
        }


        for (int i = 0; i < 5; i++) {
            new Thread(cake::decrement).start();
        }

    }
}

class Cake{
    Lock lock = new ReentrantLock();
    Condition conditionProv = lock.newCondition();
    Condition conditionCons = lock.newCondition();
    private  int cakeNumber = 0;  // 蛋糕最多只生产 10个 我就不生产了

    public void  increment(){
        lock.lock();
        try {
            // 如果大于10 ， 我就等
            while (true){
                while(cakeNumber>=10 ){
                    conditionProv.await();
                    // 去叫消费者消费
                }
                cakeNumber++;
                System.out.printf("生产蛋糕了,蛋糕库存%d\n",cakeNumber);
           //     TimeUnit.SECONDS.sleep(1);
                conditionCons.signalAll(); // 生产了就叫消费者
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }

    }

    public  void  decrement(){
        lock.lock();
        try {
            while(true){
                // 如果大于10 ， 我就等
                while(cakeNumber <=0){
                    conditionCons.await();
                }
                // 消费
                cakeNumber--;
                System.out.printf("吃蛋糕了，蛋糕还剩%d\n",cakeNumber);
         //       TimeUnit.SECONDS.sleep(1);
                // 消费了就去叫生产者生产
                conditionProv.signalAll();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}
